<template>
	<div class="app-container">
		<el-form size="small" :inline="true" v-show="showSearch" label-width="70px">
			<el-form-item label="时间范围">
				<el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :clearable="false"> </el-date-picker>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>
		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5"><div style="line-height: 30px; font-size: 15px; color: #666">生成表单</div></el-col>
			<el-col :span="1.5">
				<el-select size="small" v-model="selval" @change="exportExcel">
					<el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
				</el-select>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList" perm="erp:productData:export"></right-toolbar>
		</el-row>
		<table>
			<thead>
				<tr>
					<th v-for="(header, index) in headers" :key="index">{{ header }}</th>
				</tr>
			</thead>
			<tbody>
				<tr v-for="(row, rowIndex) in tableData" :key="rowIndex">
					<td v-for="(cell, cellIndex) in row" :key="cellIndex">{{ cell }}</td>
				</tr>
			</tbody>
		</table>
	</div>
</template>
<script>
import * as ExcelJS from "exceljs"
import { getData } from "@/api/equipment/produce/test"

export default {
	data() {
		return {
			selval: undefined,
			options: [
				{
					id: "1",
					name: "导出工时"
				}
			],
			headers: [],
			tableData: [],
			dateRange: "",
			showSearch: true,
		}
	},
	mounted() {
		this.dateRange = [this.getStartTime(), this.getEndTime()]
		this.getList()
	},
	methods: {
		/** 搜索按钮操作 */
		handleQuery() {
			this.getList()
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.dateRange = ""
			this.headers = []
			this.tableData = []
			this.$modal.msg("请选择日期范围")
		},
		getStartTime() {
			let date = new Date()
			date.setDate(1)
			let year = date.getFullYear()
			let month = date.getMonth() + 1
			month = month > 10 ? month : "0" + month
			let day = date.getDate()
			day = day > 10 ? day : "0" + day
			return year + "-" + month + "-" + day
		},
		getEndTime() {
			let date = new Date()
			let year = date.getFullYear()
			let month = date.getMonth() + 1
			let nextMonthFirthDay = new Date(year, month, 1) // 下个月的第一天
			month = month > 10 ? month : "0" + month
			let oneDay = 1000 * 60 * 60 * 24 // 一天的时间毫秒数
			let endDay = new Date(nextMonthFirthDay - oneDay)
			let day = endDay.getDate() // 本月最后一天
			day = day > 10 ? day : "0" + day
			return year + "-" + month + "-" + day
		},

		getList() {
			if (this.dateRange === "" || !this.dateRange) {
				this.$modal.msg("请选择日期范围")
				return
			}
			getData({
				beginTime: this.dateRange[0],
				finishTime: this.dateRange[1]
			}).then(response => {
				response.data.theads.unshift("序号")
				response.data.theads.push("合计")
				this.headers = response.data.theads
				response.data.infos.forEach((item, index) => {
					let total = 0
					item.forEach((i, x) => {
						if (x !== 0) {
							total += parseFloat(i)
						}
					})
					item.push(total.toFixed(2))
					item.unshift(index + 1)
					total = 0
				})
				if (response.data.infos.length > 0) {
					const columnTotals = ["合计", "/"]
					response.data.infos.forEach(row => {
						row.forEach((cell, index) => {
							if (index > 1) {
								if (!columnTotals[index]) {
									columnTotals[index] = 0
								}
								columnTotals[index] += parseFloat(cell)
							}
						})
					})
					columnTotals.forEach((item, index) => {
						if (index > 1) {
							columnTotals[index] = item.toFixed(2)
						}
					})
					response.data.infos.push(columnTotals)
				}
				this.tableData = response.data.infos
			})
			// const response = {
			// 	code: 200,
			// 	data: {
			// 		theads: ["产品编号", "管理员", "一号工人", "二号工人", "三号工人", "四号工人"],
			// 		infos: [
			// 			["00001", 123456, 123456, 123456, 123456, 123456],
			// 			["00002", 123456, 123456, 123456, 123456, 123456],
			// 			["00003", 123456, 123456, 123456, 123456, 123456],
			// 			["00004", 123456, 123456, 123456, 123456, 123456],
			// 			["00005", 123456, 123456, 123456, 123456, 123456],
			// 			["00006", 123456, 123456, 123456, 123456, 123456],
			// 			["00007", 123456, 123456, 123456, 123456, 123456],
			// 			["00008", 123456, 123456, 123456, 123456, 123456],
			// 			["00009", 123456, 123456, 123456, 123456, 123456],
			// 			["00010", 123456, 123456, 123456, 123456, 123456],
			// 			["00011", 123456, 123456, 123456, 123456, 123456],
			// 			["00012", 123456, 123456, 123456, 123456, 123456],
			// 			["00013", 123456, 123456, 123456, 123456, 123456]
			// 		]
			// 	}
			// }
			// response.data.theads.unshift("序号")
			// response.data.theads.push("合计")
			// this.headers = response.data.theads
			// response.data.infos.forEach((item, index) => {
			// 	let total = 0
			// 	item.forEach((i, x) => {
			// 		if (x !== 0) {
			// 			total += i
			// 		}
			// 	})
			// 	item.push(total)
			// 	item.unshift(index + 1)
			// 	total = 0
			// })
			// const columnTotals = ["合计", "/"]
			// response.data.infos.forEach(row => {
			// 	row.forEach((cell, index) => {
			// 		if (index > 1) {
			// 			if (!columnTotals[index]) {
			// 				columnTotals[index] = 0
			// 			}
			// 			columnTotals[index] += parseInt(cell, 10)
			// 		}
			// 	})
			// })
			// response.data.infos.push(columnTotals)
			// this.tableData = response.data.infos
		},
		exportExcel() {
			const workbook = new ExcelJS.Workbook() // 创建一个excel工作薄
			const worksheet = workbook.addWorksheet("sheet") // 创建一个工作表

			// 添加表头
			worksheet.columns = this.headers.map((item, index) => {
				return {
					header: item,
					// key: item,
					width: 15
				}
			})

			// 设置标题行的边框样式
			const row1 = worksheet.getRow(1)
			row1.height = 40
			worksheet.getRow(1).eachCell(cell => {
				cell.border = {
					top: { style: "thin" },
					left: { style: "thin" },
					bottom: { style: "thin" },
					right: { style: "thin" }
				}
				cell.font = {
					name: "黑体",
					bold: true,
					color: {
						// 注意：在 exceljs 中所有的的颜色值均为 argb 格式，且不带 # 符号
						argb: "000000"
					}
				}
				cell.fill = {
					type: "pattern",
					pattern: "solid",
					fgColor: {
						argb: "f1ccab"
					}
				}
			})
			// 设置标题行的居中对齐
			worksheet.getRow(1).eachCell(cell => {
				cell.alignment = { horizontal: "center", vertical: "middle" }
			})

			// 添加数据
			worksheet.addRows(this.tableData)

			// 设置单元格边框样式
			const borderStyle = {
				style: "thin",
				color: { argb: "000000" }
			}

			// 获取工作表的最大行数和列数
			const maxRow = worksheet.rowCount
			const maxCol = worksheet.columnCount

			// 遍历单元格
			for (let row = 1; row <= maxRow; row++) {
				for (let col = 1; col <= maxCol; col++) {
					const cell = worksheet.getCell(row, col)
					const row2 = worksheet.getRow(row)
					row2.height = 40
					cell.border = {
						top: borderStyle,
						left: borderStyle,
						bottom: borderStyle,
						right: borderStyle
					}

					// 设置居中对齐和自动换行
					cell.alignment = {
						horizontal: "center",
						vertical: "middle",
						wrapText: true
					}
				}
			}

			// 导出工作簿
			workbook.xlsx.writeBuffer().then(buffer => {
				const blob = new Blob([buffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" })
				const link = document.createElement("a")
				link.href = window.URL.createObjectURL(blob)
				link.download = "工时.xlsx"
				link.click()
				setTimeout(() => {
					this.selval = undefined
				}, 1000)
			})
		}
	}
}
</script>
<style scoped>
/* 添加一些基本的样式 */
table {
	border-collapse: collapse;
	width: 100%;
	color: #616266;
}
th,
td {
	height: 44px;
	border: 1px solid #e0e6ec;
	/* padding: 8px; */
	text-align: center;
}
th {
	background-color: #f1f1f1;
	text-align: center;
}
</style>
